package com.rex.web;

import com.rex.domain.User;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Author: RexFang
 * Version: 1.0
 * Date: 2017/11/1 21:49
 */
@RestController
@RequestMapping(value = "/restful")
public class RestfulApisController {
    private static final String SUCCESS = "success";
    private static Map<Long, User> userMap = Collections.synchronizedMap(new HashMap<>());

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<User> getUserList(){
        return new ArrayList<>(userMap.values());
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String postUser(@ModelAttribute User user){
        userMap.put(user.getId(), user);
        return SUCCESS;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable Long id){
        return userMap.get(id);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @ModelAttribute User user){
        User u = userMap.get(id);
        BeanUtils.copyProperties(user, u, "id");
        return SUCCESS;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id){
        userMap.remove(id);
        return SUCCESS;
    }
}
